"use client";

import { TimeIcon } from "@/src/icons/TimeIcon";
import { MacroAction } from "@/src/types/types.v1";
import { Box } from "@chakra-ui/react";
import { useState } from "react";

function MacroTimeAction({
  action,
  onChange,
}: {
  action: MacroAction;
  onChange: (action: MacroAction) => void;
}) {
  const [edit, setEdit] = useState(action.delay == 0);
  const [editDelay, setEditDelay] = useState(action.delay);

  const changeDelay = (delay: number) => {
    if (Number.isNaN(delay)) {
      setEditDelay(0);
    } else {
      setEditDelay(delay);
    }
  };

  const onSubmit = (evt: any) => {
    evt.stopPropagation();
    onChange({ ...action, delay: editDelay || 50 });
    setEdit(false);
  };

  return (
    <div
      className="p-4 font-semibold text-sm border border-white hover:border-blue-1 bg-[#2b2d31] rounded-lg flex gap-1 items-center justify-center [&_path]:data-[edit=true]:!fill-blue-1 data-[edit=true]:!border-blue-1 data-[edit=true]:!border-2"
      data-edit={edit}
    >
      <TimeIcon className="w-5 h-5" />
      {edit ? (
        <>
          <form onSubmit={onSubmit}>
            <input
              type="text"
              className="outline-none bg-transparent w-12 text-blue-1"
              value={editDelay == 0 ? "" : editDelay + ""}
              autoFocus
              onFocus={(evt) => evt.target.select()}
              onChange={(evt) => changeDelay(parseInt(evt.target.value))}
              onBlur={onSubmit}
            />
          </form>
        </>
      ) : (
        <Box onClick={() => setEdit(true)} className=" select-none">
          {action.delay}ms
        </Box>
      )}
    </div>
  );
}

export default MacroTimeAction;
